<template>
  <Nav />
  <div id="main">
    <router-view></router-view>
  </div>
</template>
<script setup>
import Nav from '@/components/header.vue'
import config from '@/config'
import { createAppKit } from '@reown/appkit/vue'
import { showToast } from 'vant'
import api from '@/apis'
import mitt from '@/utils/mitt'

let initMetamask = async () => {
  const appKit = createAppKit({
    adapters: [config.wagmiAdapter],
    networks: config.networks,
    projectId: config.projectId,
    // metadata,
    features: {
      analytics: true
    },
  })
  //监听appKit钱包断开
  appKit.subscribeEvents(({ data }) => {
    if (data.event === 'DISCONNECT_SUCCESS') {
      localStorage.removeItem('token')
    }
  })
  autoLogin()
}

// 登录 
const loginWithWallet = async (address) => {
  try {
    if (!address || localStorage.getItem('token')) return
    // 获取签名消息
    const {data} = await api.login.loginMessage()
    
    const signature = await window.ethereum.request({
      method: 'personal_sign',
      params: [data.message, address]
    })
    const resp = await api.login.login({ address, message:data.message, sign_message: signature })
    if(resp.code != 200){
      showToast(resp.message)
      return
    }
    localStorage.setItem('token', resp.data.token)
    mitt.emit('login')
  } catch (err) {
    console.warn('wallet login failed:', err)
  }
}

// 获取当前账户并登录
const autoLogin = async () => {
  try {
    if (!window.ethereum) return
    const accounts = await window.ethereum.request({ method: 'eth_accounts' })
    if (accounts && accounts[0]) {
      await loginWithWallet(accounts[0])
    }
  } catch (err) {
    console.warn('tryAutoLogin failed:', err)
  }
}

// 监听链接或者账户变化
if (window.ethereum) {
  window.ethereum.on('connect', async () => {
    autoLogin()
  })
  window.ethereum.on('accountsChanged', async (accounts) => {
    if (accounts && accounts[0]) {
      await loginWithWallet(accounts[0])
    }
  })
}

initMetamask()

</script>
